package com.cmdi.opensite.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cmdi.opensite.entity.Activity;
import com.cmdi.opensite.service.ActivityService;
import com.cmdi.opensite.service.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动控制器
 */
@RestController
@RequestMapping("/api/activities")
public class ActivityController {
    
    @Autowired
    private ActivityService activityService;
    
    @Autowired
    private RegistrationService registrationService;
    
    /**
     * 分页查询活动列表
     */
    @GetMapping("/page")
    public ResponseEntity<?> getActivityPage(@RequestParam(defaultValue = "1") Integer current,
                                           @RequestParam(defaultValue = "10") Integer size,
                                           @RequestParam(required = false) Long categoryId,
                                           @RequestParam(required = false) Integer status,
                                           @RequestParam(required = false) String keyword) {
        IPage<Activity> page = activityService.selectActivityPage(
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size),
            categoryId, status, keyword);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", page.getRecords());
        result.put("total", page.getTotal());
        result.put("current", current);
        result.put("size", size);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据ID获取活动详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getActivityById(@PathVariable Long id, @RequestAttribute(required = false) Long userId) {
        Activity activity = activityService.getActivityById(id);
        if (activity != null) {
            // 如果用户已登录，检查是否已报名
            if (userId != null) {
                activity.setIsRegistered(registrationService.hasRegistered(id, userId));
            }
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", activity);
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.notFound().build();
    }
    
    /**
     * 创建活动
     */
    @PostMapping
    public ResponseEntity<?> createActivity(@RequestBody Activity activity, @RequestAttribute("userId") Long userId) {
        activity.setOrganizerId(userId);
        boolean success = activityService.saveActivity(activity);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "创建成功");
            return ResponseEntity.ok(result);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "创建失败");
        return ResponseEntity.badRequest().body(result);
    }
    
    /**
     * 更新活动
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateActivity(@PathVariable Long id, @RequestBody Activity activity, @RequestAttribute("userId") Long userId) {
        activity.setId(id);
        activity.setOrganizerId(userId); // 确保组织者不变
        boolean success = activityService.saveActivity(activity);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "更新成功");
            return ResponseEntity.ok(result);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "更新失败");
        return ResponseEntity.badRequest().body(result);
    }
    
    /**
     * 更新活动状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateStatus(@PathVariable Long id, @RequestBody Map<String, Integer> statusData) {
        Integer status = statusData.get("status");
        boolean success = activityService.updateActivityStatus(id, status);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "状态更新成功");
            return ResponseEntity.ok(result);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "状态更新失败");
        return ResponseEntity.badRequest().body(result);
    }
    
    /**
     * 删除活动
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteActivity(@PathVariable Long id) {
        boolean success = activityService.deleteActivity(id);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "删除成功");
            return ResponseEntity.ok(result);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "删除失败");
        return ResponseEntity.badRequest().body(result);
    }
    
    /**
     * 获取即将开始的活动
     */
    @GetMapping("/upcoming")
    public ResponseEntity<?> getUpcomingActivities(@RequestParam(defaultValue = "5") Integer limit) {
        List<Activity> activities = activityService.getUpcomingActivities(limit);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", activities);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取热门活动
     */
    @GetMapping("/hot")
    public ResponseEntity<?> getHotActivities(@RequestParam(defaultValue = "5") Integer limit) {
        List<Activity> activities = activityService.getHotActivities(limit);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", activities);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取用户已报名的活动
     */
    @GetMapping("/registered")
    public ResponseEntity<?> getUserRegisteredActivities(@RequestParam(defaultValue = "1") Integer current,
                                                      @RequestParam(defaultValue = "10") Integer size,
                                                      @RequestAttribute("userId") Long userId) {
        IPage<Activity> page = activityService.getUserRegisteredActivities(
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size), userId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", page.getRecords());
        result.put("total", page.getTotal());
        result.put("current", current);
        result.put("size", size);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取用户创建的活动
     */
    @GetMapping("/created")
    public ResponseEntity<?> getUserCreatedActivities(@RequestParam(defaultValue = "1") Integer current,
                                                   @RequestParam(defaultValue = "10") Integer size,
                                                   @RequestAttribute("userId") Long userId) {
        IPage<Activity> page = activityService.getUserCreatedActivities(
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size), userId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", page.getRecords());
        result.put("total", page.getTotal());
        result.put("current", current);
        result.put("size", size);
        return ResponseEntity.ok(result);
    }
}